<?php
/**
 * Created by PhpStorm.
 * User: yanji
 * Date: 2018/3/31
 * Time: 9:20
 */

namespace Admin\Controller;

use think\Controller;
class ChannelManageController extends Controller
{
    public function index()
    {
        session('successTimes', null);
        session('overdueTimes', null);
        session('orders', null);
        if (!file_get_contents('./Public/Uploads/GW')) {
            mkdir('./Public/Uploads/GW');
        }
        if (I('request.status') == 0) {
            $this->display('Channel/channel_list_success');
        } else if (I('request.status') == 1) {
            $this->display('Channel/channel_list_overdue');
        }  else if (I('request.status') == 2) {
            $this->display('Channel/channel_list_s');
        }

    }

    public function twoCascades()
    {
        $city_db = M('city');
        $province = $city_db -> where('pid=0') -> select();
        $city_res = $city_db -> where('pid <> 0') -> select();
        $city = [];
        $city1 = [];
        foreach ($province as $k => $v) {
            $result = [];
            $city[$province[$k]['id']] = $province[$k]['name'];
            foreach ($city_res as $key => $value) {
                if ($province[$k]['id'] == $city_res[$key]['pid']) {
                    $result[$city_res[$key]['id']] = $city_res[$key]['name'];
                }
            }
            $city1[] = $result;
        }
        $this -> ajaxReturn([$city, $city1], 'JSON');
    }

    public function getAllChannelList()
    {
        $status = I('request.status');
        $waynum= I('request.waynum');
        $wayStatus = I('request.wayStatus');
        $province = I('request.province');
        $city = I('request.city');
        $successTimes = I('request.successMonths');//时间
        $overdueTimes = I('request.overdueMonths');//时间
        $success_l = I('request.successl');//过单率
        $successTag = I('request.successtag');
        $overduel = I('request.overduel');//过单率
        $overdueTag = I('request.overduetag');

        $admin_db = M('admin');
        $order_db = M('order');
        $city_db = M('city');
        $wayuser_db = M('wayuser');
        $user_db = M('user');
        $order_operation_db = M('order_operation');
        $order_month_pay_db = M('order_month_pay');
        $wayWhere = '';
        if ($waynum != '' && $status == 0) {
            $wayWhere = "waynum=".$waynum." and status >= 2";
            $wayusers = $wayuser_db -> where($wayWhere) -> select();
            if (!$wayusers) {
                $gw = $admin_db -> where(array('usernum' => $waynum, 'position' => 1)) -> find();
                if ($gw) {
                    $wayWhere = "admin_id=".$gw['id']." and status >= 2";
                    $wayusers = $wayuser_db -> where($wayWhere) -> select();
                    if (!$wayusers) {
                        $this -> ajaxReturn(['error' => 1, 'msg' => []], 'JSON');
                    }
                } else {
                    $this -> ajaxReturn(['error' => 1, 'msg' => []], 'JSON');
                }
            }
        } else {
            if ($province && $city) {
                $cs = $admin_db -> where(array('provinceid' => $province, 'cityid' => $city, 'position' => 3)) -> select();
            } else if ($province) {
                $cs = $admin_db -> where(array('provinceid' => $province, 'position' => 3)) -> select();
            } else {
                $cs = $admin_db -> where(array('position' => 3)) -> select();
            }
            //查询GW
            $ids = "pid in (".implode(',', array_column($cs, 'id')).")";
            $gws = $admin_db -> where($ids) -> select();
            if (($wayStatus == '2' || $wayStatus == '3') && $wayStatus != '') {
                $wayWhere = 'status='.$wayStatus;
            } else {
                $wayWhere = 'status >= 2';
            }
            $wayWhere .= " and admin_id in (".implode(',', array_column($gws, 'id')).")";
            $wayusers = $wayuser_db -> where($wayWhere) -> order('admin_id') -> select();
            if (!$wayusers) {
                $this -> ajaxReturn(['error' => '', 'msg' => []], 'JSON');
            }
        }
        //通过渠道编号查询用户
        $waynums = "waynum in (".implode(',', array_column($wayusers, 'waynum')).")";
        $users = $user_db -> where($waynums) -> select();
        //查询GW
        $gws = $admin_db -> where('position = 1') -> select();
        //查询城市经理跟省总
        $sz = $admin_db -> where('position=4 or position=3') -> select();
        //通过用户查询所有的订单
        $uids= "uid in (".implode(',', array_column($users, 'id')).")";
        $orders = $order_db -> where($uids) -> select();
        //t通过淡定查询所有的订单记录
        $orderids = "orderid in (".implode(',', array_column($orders, 'orderid')).")";;
        $orderopration = $order_operation_db -> where($orderids) -> select();
        //查询所有订单分期
        $order_month_pay = $order_month_pay_db -> where($orderids) -> select();
        //查询所有城市
        $city = $city_db -> select();
        if (count($successTimes) != 2 || !$successTimes) {
//            $curry = date('Y', time());
//            $currm = date('m', time());
//            $y = date('Y', 1517363215);
//            $m = date('m', 1517363215);
//            $curr = ($curry * 12 + $currm) - ($y * 12 + $m);
//            $successTimes  = [1, $curr+1];
            $successTimes = [1, 12];
        }
        if (count($overdueTimes) != 2 || !$overdueTimes) {
//            $curry = date('Y', time());
//            $currm = date('m', time());
//            $y = date('Y', 1517363215);
//            $m = date('m', 1517363215);
//            $curr = ($curry * 12 + $currm) - ($y * 12 + $m);
//            $overdueTimes  = [1, $curr+1];
            $overdueTimes = [1, 12];
        }
        $data = $this -> getAllChannelInfo($orders, $orderopration, $order_month_pay, $wayusers, $users, $gws, $sz, $city, $successTimes, $overdueTimes, $success_l, $overduel, $successTag, $overdueTag, $waynum);
        $orderM = D('order');
        session('successTimes', base64_encode(json_encode($orderM -> getDates($successTimes[0], $successTimes[1]))));
        session('overdueTimes', base64_encode(json_encode($orderM -> getDates($overdueTimes[0], $overdueTimes[1]))));
        session('orders', base64_encode(json_encode($data)));
        $this -> ajaxReturn(['error' => '', 'msg' => $data], 'JSON');
    }

    public function exportToExcelAllChannel()
    {
        $status = I('request.status');
        $filterIndexs = I('request.filterIndexs');
        if ($status != 5) {
            $admin_db = M('admin');
            $city_db = M('city');
            $order_db = M('order');
            $wayuser_db = M('wayuser');
            $user_db = M('user');
            $order_operation_db = M('order_operation');
            $order_month_pay_db = M('order_month_pay');
            //查询所有渠道
            $wayusers = $wayuser_db -> where('status >= 2') -> order('admin_id') -> select();
            $waynums = "waynum in (".implode(',', array_column($wayusers, 'waynum')).")";
            //查询跟渠道有关的用户
            $users = $user_db -> where($waynums) -> select();
            //查询所有GW
            $gws = $admin_db -> where('position=1') -> select();
            //查询所有的省总 查询所有城市经理
            $sz = $admin_db -> where('(position=4 or position=3) and test_sign <> 1') -> select();
            //查询所有城市
            $city = $city_db -> select();
            //查询订单
            $orderM = D('order');
            //获取导出时间
            $times = $this -> get_d_m($status);
            $time = strtotime($times[0].'-1');
            $arr = explode('-', $times[count($times)-1]);
            $time1 = strtotime($orderM -> get_y_m_d($arr[0], $arr[1]));
            //根据时间查询所有的订单
            $uids = " and uid in (".implode(',', array_column($users, 'id')).")";
            $orderWhere = "create_time >=".$time.' and create_time <='.$time1.$uids;
            $orders = $order_db -> where($orderWhere) -> select();
            //根据订单ID查询订单记录
            $operationWhere = "orderid in (".implode(',', array_column($orders, 'orderid')).")";
            $order_operation = $order_operation_db -> where($operationWhere) -> select();
            $order_month_pay = $order_month_pay_db -> where($operationWhere) -> select();
            $data = $this -> getAllChannelInfo($orders, $order_operation, $order_month_pay, $wayusers, $users, $gws, $sz, $city, $times, $times, [0,100], [0,100], [],[],null, true);
        } else {
            $data = json_decode(base64_decode(session('orders')), true);
        }
        $titles = [
            '序号',
            '渠道编号',
            '创建日期',
            '当前状态',
            'GW姓名',
            'GW岗位号',
            '城市',
            'CS岗位号',
            '省份',
            'SZ岗位号'
        ];

        if ($status == 5) {
            $times = json_decode(base64_decode(session('successTimes')), true);
        }
        $success = true;
        foreach ($times as $k => $v) {
            if ($success) {
                $orderTotalCount = '总过单数';
                $orderTotalRatio = '总过单比';
                $orderTotalRate = '总过单率';
                array_push($titles, $orderTotalCount);
                array_push($titles, $orderTotalRatio);
                array_push($titles, $orderTotalRate);
                $success = false;
            }
            if ($status == 5) {
                if ($k == 0) {
                    $month = '当月';
                } else if ($k == 1) {
                    $month = '上月';
                } else {
                    $month = '第'.($k+1).'月';
                }
                $orderCount = $month.'过单数';
                $orderRatio = $month.'过单比';
                $orderRate = $month.'过单率';
            } else {
                $orderCount = $times[$k].'月过单数';
                $orderRatio = $times[$k].'月过单比';
                $orderRate = $times[$k].'月过单率';
            }
            array_push($titles, $orderCount);
            array_push($titles, $orderRatio);
            array_push($titles, $orderRate);
        }
        $overdue = true;
        foreach ($times as $k => $v) {
            if ($overdue) {
                $orderTotalCount = '总逾期数';
                $orderTotalRatio = '总逾期比';
                $orderTotalRate = '总逾期率';
                array_push($titles, $orderTotalCount);
                array_push($titles, $orderTotalRatio);
                array_push($titles, $orderTotalRate);
                $overdue = false;
            }
            if ($status == 5) {
                if ($k == 0) {
                    $month = '当月';
                } else if ($k == 1) {
                    $month = '上月';
                } else {
                    $month = '第'.($k+1).'月';
                }
                $orderCount = $month.'逾期数';
                $orderRatio = $month.'逾期比';
                $orderRate = $month.'逾期率';
            } else {
                $orderCount = $times[$k].'月逾期数';
                $orderRatio = $times[$k].'月逾期比';
                $orderRate = $times[$k].'月逾期率';
            }
            array_push($titles, $orderCount);
            array_push($titles, $orderRatio);
            array_push($titles, $orderRate);
        }
        //添加数据
        $results = [];
        foreach ($data as $k => $v) {
            $gwStatus = '激活';$result = [];
            if ($data[$k]['status'] == 3) $gwStatus = '关闭';
            $result[] = $k+1;
            $result[] = $data[$k]['waynum'];
            $result[] = $data[$k]['time'];
            $result[] = $gwStatus;
            $result[] = $data[$k]['gwname'];
            $result[] = $data[$k]['gwusernum'];
            $result[] = $data[$k]['city'];
            $result[] = $data[$k]['csusernum'];
            $result[] = $data[$k]['province'];
            $result[] = $data[$k]['szusernum'];
            $successOrders = $data[$k]['successOrders'];
            foreach ($successOrders as $key => $v) {
                if ($key == 0) {
                    $result[] = $successOrders[$key]['orderTotalCount'];
                    $result[] = $successOrders[$key]['orderTotalRatio'];
                    $result[] = round($successOrders[$key]['orderTotalRate'], 2).'%';
                } else {
                    $result[] = $successOrders[$key]['orderCount'];
                    $result[] = $successOrders[$key]['orderRatio'];
                    $result[] = round($successOrders[$key]['orderRate'], 2).'%';
                }
            }
            $overdueOrders = $data[$k]['overdueOrders'];
            foreach ($overdueOrders as $key => $v) {
                if ($key == 0) {
                    $result[] = $overdueOrders[$key]['orderTotalCount'];
                    $result[] = $overdueOrders[$key]['orderTotalRatio'];
                    $result[] = round($overdueOrders[$key]['orderTotalRate'], 2).'%';
                } else {
                    $result[] = $overdueOrders[$key]['orderCount'];
                    $result[] = $overdueOrders[$key]['orderRatio'];
                    $result[] = round($overdueOrders[$key]['orderRate'], 2).'%';
                }
            }
            $results[] = $result;
        }
        if ($status == 5 && count($filterIndexs) > 1) {
            foreach ($titles as $k => $v) {
                if (!in_array($k.'', $filterIndexs)) {
                    unset($titles[$k]);
                }
            }
            foreach ($results as $key => $value) {
                foreach ($value as $k => $v) {
                    if (!in_array($k.'', $filterIndexs)) {
                        unset($results[$key][$k]);
                    }
                }
            }
        }
        $_savePath = ExportExcelTable($titles, $results, 'sheet', time(),'./Public/Uploads/GW/');
        $path = 'http://'.$_SERVER['SERVER_NAME'].substr($_savePath, 1, strlen($_savePath));
        $this -> ajaxReturn(['path' => $path], 'JSON');
    }

    public function getAllChannelInfo($orders, $orderopration, $order_month_pay, $wayusers, $users, $gws, $sz, $city, $successTimes, $overdueTimes, $success_l, $overduel, $successTag = [],  $overdueTag = [], $waynum = null, $istimes = false)
    {
        $successOrders = $this -> getSuccessGwOrder($orders, $orderopration, $users);
        $overdueOrders = $this -> getOverudeGwOrder($order_month_pay, $users);
        $data = [];$s = 0; $orderM = D('order');
        foreach ($wayusers as $k => $v) {
            $result = [];
            $result2 = [];
            foreach ($successOrders as $key => $value) {
                //相等取出订单放入另外一个数组中
                if ($wayusers[$k]['waynum'] == $successOrders[$key]['waynum']) {
                    $result[] = $successOrders[$key];
                }
            }
            foreach ($overdueOrders as $key => $value) {
                if ($wayusers[$k]['waynum'] == $overdueOrders[$key]['waynum']) {
                    $result2[] = $overdueOrders[$key];
                }
            }
            //根据订单和时间获取过单数据
            $result = $orderM -> getSuccessOrder($result, $successTimes, $istimes);
            $result2 = $orderM -> getOverdueOrder($result2, $orders, $overdueTimes, $istimes);

            foreach ($gws as $key => $value) {
                if ($wayusers[$k]['admin_id'] == $gws[$key]['id']) {
                    $wayusers[$k]['pid'] = $gws[$key]['pid'];
                    $wayusers[$k]['gwusernum'] = $gws[$key]['usernum'];
                    $wayusers[$k]['gwname'] = $gws[$key]['name'];
                    $wayusers[$k]['provinceid'] = $gws[$key]['provinceid'];
                    $wayusers[$k]['cityid'] = $gws[$key]['cityid'];
                    break;
                }
            }
            //取出城市经理的usernum和省总的usernum
            foreach ($sz as $key => $value) {
                if ($wayusers[$k]['pid'] == $sz[$key]['id']) {
                    $wayusers[$k]['csusernum'] = $sz[$key]['usernum'];
                }
                if ($sz[$key]['position'] == 4 && $wayusers[$k]['provinceid'] == $sz[$key]['provinceid']) {
                    $wayusers[$k]['szusernum'] = $sz[$key]['usernum'];
                }
            }
            //取出GW所属城市
            foreach ($city as $key => $value) {
                if ($wayusers[$k]['provinceid'] == $city[$key]['id']) {
                    $wayusers[$k]['province'] = $city[$key]['name'];
                }
                if ($wayusers[$k]['cityid'] == $city[$key]['id']) {
                    $wayusers[$k]['city'] = $city[$key]['name'];
                }
            }
            $successRate = false;
            foreach ($result as $key => $value) {
                $r = $result[$key];
                if (count($success_l) == 2 &&  $r['orderTotalRate'] >= $success_l[0] && $r['orderTotalRate'] <= $success_l[1]) {
                    $successRate = true;
                }
                if (count($success_l) == 2 &&  $r['orderRate'] >= $success_l[0] && $r['orderRate'] <= $success_l[1]) {
                    $successRate = true;
                }
                if (count($successTag) == 2 &&  $r['orderTotalRate'] >= $successTag[0] && $r['orderTotalRate'] <= $successTag[1]) {
                    $result[$key]['tag'] = true;
                }
                if (count($successTag) == 2 &&  $r['orderRate'] >= $successTag[0] && $r['orderRate'] <= $successTag[1]) {
                    $result[$key]['tag'] = true;
                }
            }
            $overdueRate = false;
            foreach ($result2 as $key => $value) {
                $r = $result2[$key];
                if (count($overduel) == 2 &&  $r['orderTotalRate'] >= $overduel[0] && $r['orderTotalRate'] <= $overduel[1]) {
                    $overdueRate = true;
                }
                if (count($overduel) == 2 &&  $r['orderRate'] >= $overduel[0] && $r['orderRate'] <= $overduel[1]) {
                    $overdueRate = true;
                }
                if (count($overdueTag) == 2 &&  $r['orderTotalRate'] >= $overdueTag[0] && $r['orderTotalRate'] <= $overdueTag[1]) {
                    $result2[$key]['tag'] = true;
                }
                if (count($overdueTag) == 2 &&  $r['orderRate'] >= $overdueTag[0] && $r['orderRate'] <= $overdueTag[1]) {
                    $result2[$key]['tag'] = true;
                }
            }
            if (!$successRate && !$overdueRate && !$waynum) continue;
            $res = [];
            $res['successOrders'] = [];
            $res['overdueOrders'] = [];
            if ($successRate || $waynum) {
                $res['successOrders'] = $result;
            }
            if ($overdueRate || $waynum) {
                $res['overdueOrders'] = $result2;
            }
            $res['status'] = $wayusers[$k]['status'];
            $res['waynum'] = $wayusers[$k]['waynum'];
            $res['time'] = date('Y-m-d', $wayusers[$k]['create_time']);
            $res['gwname'] = $wayusers[$k]['gwname'];
            $res['gwusernum'] = $wayusers[$k]['gwusernum'];
            $res['csusernum'] = $wayusers[$k]['csusernum'];
            $res['szusernum'] = $wayusers[$k]['szusernum'];
            $res['province'] = $wayusers[$k]['province'];
            $res['city'] = $wayusers[$k]['city'];
            $res['successTimes'] = $successTimes;
            $res['overdueTimes'] = $overdueTimes;
            $data[$s] = $res;
            $s ++;
        }
        return $data;
    }

    public function getSuccessGwOrder($orders, $orderopration, $users)
    {
        //向所有订单中添加GW的usernum
        foreach ($orders as $k => $v) {
            foreach ($orderopration as $key => $value) {
                if ($orders[$k]['orderid'] == $orderopration[$key]['orderid'] &&
                    ($orderopration[$key]['status'] == 2 || $orderopration[$key]['status'] == -1)) {
                    $orders[$k]['success_time'] = $orderopration[$key]['create_time'];
                    break;
                }
            }
            foreach ($users as $key => $value) {
                if ($orders[$k]['uid'] == $users[$key]['id']) {
                    $orders[$k]['waynum'] = $users[$key]['waynum'];
                    break;
                }
            }
        }
        return $orders;
    }

    public function getOverudeGwOrder($order_month_pay, $users)
    {
        //向所有订单中添加GW的usernum
        foreach ($users as $key => $value) {
            foreach ($order_month_pay as $k => $v) {
                if ($users[$key]['id'] == $order_month_pay[$k]['uid']) {
                    $order_month_pay[$k]['waynum'] = $users[$key]['waynum'];
                }
            }
        }
        return $order_month_pay;
    }

    public function channelList()
    {
        $waynum = I('request.waynum');
        $status = I('request.status');
        $wayStatus = I('request.wayStatus');
        $province = I('request.province');
        $city = I('request.city');
        $times = I('request.times');//时间
        $rates = I('request.rates');//过单率
        $tags = I('request.tags');
        $msg = I('request.msg');
        $wayuser_db = M('wayuser');
        $admin_db = M('admin');
        $order_db = M('order');
        $city_db = M('city');
        $user_db = M('user');
        $order_operation_db = M('order_operation');
        //查询渠道
        $wayWhere = '';
        if ($waynum != '' && $status == 0) {
            $wayWhere = "waynum=".$waynum." and status >= 2";
            $wayusers = $wayuser_db -> where($wayWhere) -> select();
            if (!$wayusers) {
                $gw = $admin_db -> where(array('usernum' => $waynum, 'position' => 1)) -> find();
                if ($gw) {
                    $wayWhere = "admin_id=".$gw['id']." and status >= 2";
                    $wayusers = $wayuser_db -> where($wayWhere) -> select();
                    if (!$wayusers) {
                        $this -> ajaxReturn(['error' => 1, 'msg' => []], 'JSON');
                    }
                } else {
                    $this -> ajaxReturn(['error' => 1, 'msg' => []], 'JSON');
                }
            }
        } else {
            if ($province && $city) {
                $cs = $admin_db -> where(array('provinceid' => $province, 'cityid' => $city, 'position' => 3)) -> select();
            } else if ($province) {
                $cs = $admin_db -> where(array('provinceid' => $province, 'position' => 3)) -> select();
            } else {
                $cs = $admin_db -> where(array('position' => 3)) -> select();
            }
            //查询GW
            $ids = "pid in (".implode(',', array_column($cs, 'id')).")";
            $gws = $admin_db -> where($ids) -> select();
            if (($wayStatus == '2' || $wayStatus == '3') && $wayStatus != '') {
                $wayWhere = 'status='.$wayStatus;
            } else {
                $wayWhere = 'status >= 2';
            }
            $wayWhere .= " and admin_id in (".implode(',', array_column($gws, 'id')).")";
            $wayusers = $wayuser_db -> where($wayWhere) -> order('admin_id') -> select();
            if (!$wayusers) {
                $this -> ajaxReturn(['error' => '', 'msg' => []], 'JSON');
            }
        }
        //通过渠道号查询用户
        $waynums = "waynum in (".implode(',', array_column($wayusers, 'waynum')).")";
        $users = $user_db -> where($waynums) -> select();
        //查询GW
        $gws = $admin_db -> where('position=1') -> select();
        //查询城市经理跟省总
        $sz = $admin_db -> where('(position=4 or position=3) and test_sign <> 1') -> select();
        //查询所有的订单
        $uids = "uid in (".implode(',', array_column($users, 'id')).")";
        $orders = $order_db -> where($uids) -> select();
        //查询所有的订单记录
        $orderids = "orderid in (".implode(',', array_column($orders, 'orderid')).")";
        $orderoperation = $order_operation_db -> where($orderids) -> select();
        //查询所有城市
        $city = $city_db -> select();
        if (count($times) != 2 || !$times) {
//            $curry = date('Y', time());
//            $currm = date('m', time());
//            $y = date('Y', 1517363215);
//            $m = date('m', 1517363215);
//            $curr = ($curry * 12 + $currm) - ($y * 12 + $m);
//            $times = [1, $curr + 1];
            $times = [1, 12];
        }
        $data = $this -> getChannelInfo($msg, $orders, $orderoperation, $wayusers, $users,$gws, $sz, $city, $times, $rates, $tags);
        $orderM = D('order');
        session('msg', $msg);
        session('successTimes', base64_encode(json_encode($orderM -> getDates($times[0], $times[1]))));
        session('orders', base64_encode(json_encode($data)));
        $this -> ajaxReturn(['error' => '', 'msg' => $data], 'JSON');
    }

    public function exportToExcelChannel()
    {
        $status = I('request.status');
        $filterIndexs = I('request.filterIndexs');
        $msg = I('request.msg');
        if ($status != 5) {
            $admin_db = M('admin');
            $city_db = M('city');
            $order_db = M('order');
            $wayuser_db = M('wayuser');
            $user_db = M('user');
            $order_operation_db = M('order_operation');
            //查询所有渠道
            $wayusers = $wayuser_db -> where('status >= 2') -> order('admin_id') -> select();
            $waynums = "waynum in (".implode(',', array_column($wayusers, 'waynum')).")";
            //查询跟渠道有关的用户
            $users = $user_db -> where($waynums) -> select();
            //查询所有GW
            $gws = $admin_db -> where('position=1') -> select();
            //查询所有的省总 查询所有城市经理
            $sz = $admin_db -> where('(position=4 or position=3) and test_sign <> 1') -> select();
            //查询所有城市
            $city = $city_db -> select();
            //查询订单
            $orderM = D('order');
            //获取导出时间
            $times = $this -> get_d_m($status);
            $time = strtotime($times[0].'-1');
            $arr = explode('-', $times[count($times)-1]);
            $time1 = strtotime($orderM -> get_y_m_d($arr[0], $arr[1]));
            //根据时间查询所有的订单
            $uids = " and uid in (".implode(',', array_column($users, 'id')).")";
            $orderWhere = "create_time >=".$time.' and create_time <='.$time1.$uids;
            $orders = $order_db -> where($orderWhere) -> select();
            //根据订单ID查询订单记录
            $operationWhere = "orderid in (".implode(',', array_column($orders, 'orderid')).")";
            $order_operation = $order_operation_db -> where($operationWhere) -> select();
            //获取所有的GW信息
            $data = $this -> getChannelInfo($msg, $orders, $order_operation, $wayusers, $users, $gws, $sz, $city, $times, [0,100],[], true);
        } else {
            $msg = session('msg');
            $times = json_decode(base64_decode(session('successTimes')), true);
            $data = json_decode(base64_decode(session('orders')), true);
        }

        if ($msg == 'success') {
            $totalCount = '总过单数';
            $totalRaio = '总过单比';
            $totalRate = '总过单率';
        } else if ($msg == 'overdue') {
            $totalCount = '总逾期数';
            $totalRaio = '总逾期比';
            $totalRate = '总逾期率';
        }
        $titles = array(
            '序号',
            '渠道编号',
            '创建日期',
            '当前状态',
            'GW姓名',
            'GW岗位号',
            '城市',
            'CS岗位号',
            '省份',
            'SZ岗位号',
            $totalCount,
            $totalRaio,
            $totalRate,
        );
        foreach ($times as $k => $v) {
            if ($status != 5) {
                if ($msg == 'success') {
                    $month1 = $v.'月过单数';
                    $month2 = $v.'月过单比';
                    $month3 = $v.'月过单率';
                } else if ($msg == 'overdue') {
                    $month1 = $v.'月逾期数';
                    $month2 = $v.'月逾期比';
                    $month3 = $v.'月逾期率';
                }
            } else {
                if ($k == 0) {
                    $month = '当月';
                } else if ($k == 1) {
                    $month = '上月';
                } else {
                    $month = '第'.($k+1).'月';
                }
                if ($msg == 'success') {
                    $month1 = $month.'过单数';
                    $month2 = $month.'过单比';
                    $month3 = $month.'过单率';
                } else if ($msg == 'overdue') {
                    $month1 = $month.'逾期数';
                    $month2 = $month.'逾期比';
                    $month3 = $month.'逾期率';
                }
            }
            array_push($titles, $month1);
            array_push($titles, $month2);
            array_push($titles, $month3);
        }
        $results = [];
        foreach ($data as $k => $v) {
            $gwStatus = '激活'; $result = [];
            if ($data[$k]['status'] == 3) $gwStatus = '关闭';
            $result[] = $k+1;
            $result[] = $data[$k]['waynum'];
            $result[] = $data[$k]['time'];
            $result[] = $gwStatus;
            $result[] = $data[$k]['gwname'];
            $result[] = $data[$k]['gwusernum'];
            $result[] = $data[$k]['city'];
            $result[] = $data[$k]['csusernum'];
            $result[] = $data[$k]['province'];
            $result[] = $data[$k]['szusernum'];
            $orders = $data[$k]['orders'];
            foreach ($orders as $key => $value) {
                if ($key == 0) {
                    $result[] = $orders[$key]['orderTotalCount'];
                    $result[] = $orders[$key]['orderTotalRatio'];
                    $result[] = round($orders[$key]['orderTotalRate'], 2).'%';
                } else {
                    $result[] = $orders[$key]['orderCount'];
                    $result[] = $orders[$key]['orderRatio'];
                    $result[] = round($orders[$key]['orderRate'], 2).'%';
                }
            }
            $results[] = $result;
        }
        if ($status == 5 && count($filterIndexs) > 1) {
            foreach ($titles as $k => $v) {
                if (!in_array($k.'', $filterIndexs)) {
                    unset($titles[$k]);
                }
            }
            foreach ($results as $key => $value) {
                foreach ($value as $k => $v) {
                    if (!in_array($k.'', $filterIndexs)) {
                        unset($results[$key][$k]);
                    }
                }
            }
        }
        $_savePath = ExportExcelTable($titles, $results, 'sheet', time(),'./Public/Uploads/GW/');
        $path = 'http://'.$_SERVER['SERVER_NAME'].substr($_savePath, 1, strlen($_savePath));
        $this -> ajaxReturn(['path' => $path], 'JSON');
    }

    public function getChannelInfo($msg, $orders, $orderoperation, $wayusers, $users, $gws, $sz, $city, $times, $rates, $tags, $istimes = false)
    {
        if ($msg == 'success') {
            //获取通过的订单
            $ordersList = $this -> getSuccessGwOrder($orders, $orderoperation, $users);
        } else if ($msg == 'overdue') {
            //获取逾期的订单
            $order_month_pay_db = M('order_month_pay');
            $orderids = "orderid in (".implode(',', array_column($orders, 'orderid')).")";
            $order_month_pay = $order_month_pay_db -> where($orderids) -> select();
            $ordersList = $this -> getOverudeGwOrder($order_month_pay, $users);
        }

        $data = [];$s = 0; $orderM = D('order');
        foreach ($wayusers as $k => $v) {
            $result = [];
            foreach ($ordersList as $key => $value) {
                //相等取出订单放入另外一个数组中
                if ($wayusers[$k]['waynum'] == $ordersList[$key]['waynum']) {
                    $result[] = $ordersList[$key];
                }
            }
            //根据订单和时间获取过单数据
            if ($msg == 'success') {
                $result = $orderM -> getSuccessOrder($result, $times, $istimes);
            } else if ($msg == 'overdue') {
                $result = $orderM -> getOverdueOrder($result, $orders, $times, $istimes);
            }

            foreach ($gws as $key => $value) {
                if ($wayusers[$k]['admin_id'] == $gws[$key]['id']) {
                    $wayusers[$k]['pid'] = $gws[$key]['pid'];
                    $wayusers[$k]['gwusernum'] = $gws[$key]['usernum'];
                    $wayusers[$k]['gwname'] = $gws[$key]['name'];
                    $wayusers[$k]['provinceid'] = $gws[$key]['provinceid'];
                    $wayusers[$k]['cityid'] = $gws[$key]['cityid'];
                    $wayusers[$k]['province'] = $city[$gws[$key]['provinceid'] - 1]['name'];
                    $wayusers[$k]['city'] = $city[$gws[$key]['cityid'] - 1]['name'];
                    break;
                }
            }

            //取出城市经理的usernum和省总的usernum
            foreach ($sz as $key => $value) {
                if ($wayusers[$k]['pid'] == $sz[$key]['id']) {
                    $wayusers[$k]['csusernum'] = $sz[$key]['usernum'];

                }
                if ($sz[$key]['position'] == 4 && $wayusers[$k]['provinceid'] == $sz[$key]['provinceid']) {
                    $wayusers[$k]['szusernum'] = $sz[$key]['usernum'];
                }
            }
//            取出GW所属城市
//            foreach ($city as $key => $value) {
//                if ($wayusers[$k]['provinceid'] == $city[$key]['id']) {
//                    $wayusers[$k]['province'] = $city[$key]['name'];
//                }
//                if ($wayusers[$k]['cityid'] == $city[$key]['id']) {
//                    $wayusers[$k]['city'] = $city[$key]['name'];
//                }
//            }

            $ratesStatus = false;
            foreach ($result as $key => $value) {
                $r = $result[$key];
                if (count($rates) == 2 &&  $r['orderTotalRate'] >= $rates[0] && $r['orderTotalRate'] <= $rates[1]) {
                    $ratesStatus = true;
                }
                if (count($rates) == 2 &&  $r['orderRate'] >= $rates[0] && $r['orderRate'] <= $rates[1]) {
                    $ratesStatus = true;
                }
                if (count($tags) == 2 && $r['orderTotalRate'] >= $tags[0] && $r['orderTotalRate'] <= $tags[1]) {
                    $result[$key]['tag'] = true;
                }
                if (count($tags) == 2 &&  $r['orderRate'] >= $tags[0] && $r['orderRate'] <= $tags[1]) {
                    $result[$key]['tag'] = true;
                }
            }
            if (!$ratesStatus) continue;
            $res = [];
            $res['status'] = $wayusers[$k]['status'];
            $res['waynum'] = $wayusers[$k]['waynum'];
            $res['time'] = date('Y-m-d', $wayusers[$k]['create_time']);
            $res['gwname'] = $wayusers[$k]['gwname'];
            $res['gwusernum'] = $wayusers[$k]['gwusernum'];
            $res['csusernum'] = $wayusers[$k]['csusernum'];
            $res['szusernum'] = $wayusers[$k]['szusernum'];
            $res['province'] = $wayusers[$k]['province'];
            $res['city'] = $wayusers[$k]['city'];
            $res['times'] = $times;
            $res['orders'] = $result;
            $data[$s] = $res;
            $s ++;
        }
        return $data;
    }

    public function get_d_m($status)
    {
        $time = [];
        if ($status == 1) {
            $y = date('Y', time());
            $y = $y - 1;
            for ($i = 1; $i<= 12; $i ++ ) {
                if ($i <= 9) {
                    $times[] = $y.'-0'.$i;
                } else {
                    $times[] = $y.'-'.$i;
                }
            }
        } else if ($status == 2) {
            $y = date('Y', time());
            $m = date('m', time());
            if ($m <= 3) {
                $times = [$y.'-'.'01', $y.'-'.'02', $y.'-'.'03'];
            } else if ($m >= 4 && $m <=6) {
                $times = [$y.'-'.'04', $y.'-'.'05', $y.'-'.'06'];
            } else if ($m >=7 && $m <= 9) {
                $times = [$y.'-'.'07', $y.'-'.'08', $y.'-'.'09'];
            } else if ($m >= 10 && $m <= 12) {
                $times = [$y.'-'.'10', $y.'-'.'11', $y.'-'.'12'];
            }
        } else if ($status == 3) {
            $y = date('Y', time());
            $m = date('m', time());
            $m = $m - 1;
            if ($m <= 0) {
                $y = $y - 1;
                $m = 12;
            }
            $times = [$y.'-'.$m];
        } else if ($status == 4) {
            $y = date('Y', time());
            $m = date('m', time());
            $times = [$y.'-'.$m];
        }
        return $times;
    }
}